import { prisma } from '../lib/database.js'
import bcrypt from 'bcryptjs'

async function testAuth() {
  console.log('🔐 Testing authentication...')

  try {
    // 查找测试用户
    const user = await prisma.developer.findUnique({
      where: { email: 'test@example.com' }
    })

    if (!user) {
      console.log('❌ Test user not found')
      return
    }

    console.log(`✅ Found user: ${user.username} (${user.email})`)
    console.log(`   Status: ${user.status}`)
    console.log(`   Verified: ${user.verified}`)
    console.log(`   Password hash: ${user.passwordHash.substring(0, 20)}...`)

    // 测试密码验证
    const testPassword = 'password123'
    const isValid = await bcrypt.compare(testPassword, user.passwordHash)
    
    console.log(`🔑 Password verification for "${testPassword}": ${isValid ? '✅ Valid' : '❌ Invalid'}`)

    if (!isValid) {
      // 重新生成正确的密码哈希
      console.log('🔧 Regenerating password hash...')
      const newHash = await bcrypt.hash(testPassword, 12)
      
      await prisma.developer.update({
        where: { id: user.id },
        data: { passwordHash: newHash }
      })
      
      console.log('✅ Password hash updated')
      
      // 再次验证
      const isValidNow = await bcrypt.compare(testPassword, newHash)
      console.log(`🔑 New password verification: ${isValidNow ? '✅ Valid' : '❌ Invalid'}`)
    }

  } catch (error) {
    console.error('❌ Error testing auth:', error)
    throw error
  }
}

testAuth()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
